package com.zhss.designpattern.observer;


import java.util.Observable;
import java.util.Observer;

public class ObserverPatternDemoPractice {

    public static void main(String[] args) {
        Subject subject = new Subject(0);
        //注册一个观察者
        subject.addObserver(new ConcreteObserve());
        //改变状态
        subject.setState(1);
        subject.setState(2);
    }

    /**
     * 被观察者
     */
    public static class Subject extends Observable {

        private Integer state;

        public Subject(Integer state) {
            this.state = state;
        }
        public Integer getState() {
            return  state;
        }

        public void setState(Integer state) {
        	this.state=state;
            //通知观察者
            this.setChanged();
//            this.notifyObservers(state);
            this.notifyObservers();
        }

    }

    /**
     * 观察者
     */
    public static class ConcreteObserve implements Observer {
        public void update(Observable o, Object arg) {
            //第一种，传递更新过来
//            Integer state = (Integer) arg;
//            System.out.println("被观察者给你说，状态更新成了： " + state);

			//第二种，自己获取更新
           Subject subject = (Subject) o;
            System.out.println("被观察者给你说，状态更新成了： " + subject.getState());


        }
    }


}
